/*
 * @Descripttion: 
 * @version: 
 * @Author: yuxintao
 * @Date: 2022-04-21 10:59:11
 * @LastEditors: yuxintao
 * @LastEditTime: 2022-04-21 12:35:23
 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int sockfd;
char recvbuf[1024];
#define MCAST_ADDR "224.0.2.111"
#define MCAST_PORT 8888

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "main filename\n");
        return 1;
    }
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in local_addr;
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(MCAST_PORT);
    int yes = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)) < 0) {
        perror("setsockopt SO_REUSEPORT");
        exit(1);
    }
    if (bind(sockfd, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind");
        exit(1);
    }
    
    struct ip_mreq mreq;
    mreq.imr_interface.s_addr = INADDR_ANY; 
    mreq.imr_multiaddr.s_addr = inet_addr(MCAST_ADDR);//多播地址
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt IP_ADD_MEMBERSHIP");
        exit(1);
    }
    int loop = 1;
    if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) < 0) {
        perror("setsockopt IP_MULTICAST_LOOP");
        exit(1);
    }
    struct sockaddr_in server;
    int len;
    int sum = 0;
    FILE* fp = fopen(argv[1], "w");
    if (fp == NULL) {
        perror("fopen");
        exit(1);
    }
    while (1) {
        memset(recvbuf, 0, sizeof(recvbuf));
        int tmp = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&server, &len);
        if (strncmp(recvbuf, "over", 4) == 0) {
            memset(recvbuf, 0, sizeof(recvbuf));
            sprintf(recvbuf, "%d byte", sum);
            fputs(recvbuf, fp);
            fclose(fp);
            break;
        } else {
            sum += tmp;
            fputs(recvbuf, fp);
        }
    }
    if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt IP_DROP_MEMBERSHIP");
        exit(1);
    }
    close(sockfd);
    return 0;
}